package it.patterns.structural.proxy;

/**
 * Provide a surrogate or placeholder for another object to control access to
 * it.
 * 
 * The Proxy pattern introduces a level of indirection when accessing an object.
 * 
 * Applicability:
 * 
 * <ul>
 * <li>Remote proxy: provide a local representative for an object in a different
 * address space</li>
 * <li>Virtual proxy: create expensive object on demand</li>
 * <li>Protection proxy: control access to the original object.</li>
 * <li></li>
 * </ul>
 * 
 * <img src="Proxy.jpg" alt="Pattern Structure"/>
 * 
 * @author Luca D'Onofrio
 * 
 * @category Structural Pattern
 * @see "Design Patterns - Element of Reusable Object Oriented Software (Gamma,Helm, Johnson, Vlissides)"
 * 
 * @version 1.0
 * 
 */
public class Proxy extends SubjectInterface {
	private RealSubject realHandler;
	private int lineNumber;
	private String lineText;

	public Proxy(String fName) {
		super(fName);
		System.out.println("(creating a proxy cache)");
	}

	public String getContent() {
		if (realHandler == null)
			realHandler = new RealSubject(fileName);
		return realHandler.getContent();
	}

	public String getLine(int requestedLine) {
		if (requestedLine == lineNumber) {
			System.out.println("(accessing from proxy cache)");
			return lineText;
		} else {
			if (realHandler == null)
				realHandler = new RealSubject(fileName);
			lineText = realHandler.getLine(requestedLine);
			lineNumber = requestedLine;
		}
		return lineText;
	}

}
